<template>
  <div name="waitingQueueManagement" class=management>
    <el-form :inline="true" :model="searchForm">
      <!--搜索框-->
      <el-form-item>
        <el-input
            v-model="searchForm.params.key"
            placeholder="通过候诊、医生和患者id搜索 或者医生名字"
            clearable>
        </el-input>
      </el-form-item>


      <el-form-item>
        <el-button @click="getListInfo">搜索</el-button>
        <el-button type="primary" @click="dialogFormVisible = true" >新增</el-button>
        <!--确认按钮-->
        <el-popconfirm title="确定要删除这些记录吗？"
                       @confirm="delHandle(null)"
                       style="margin-left: 10px;">
          <el-button type="danger"
                     slot="reference"
                     :disabled="delBtnStu">批量删除</el-button>
        </el-popconfirm>

      </el-form-item>
    </el-form>

    <el-table
        ref="multipleTable"
        border
        stripe
        :data="ListInfo"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>

      <el-table-column
          prop="queueId"
          label="候诊id"
          width="100">
      </el-table-column>
      <el-table-column
          prop="doctorId"
          label="医生id"
          width="100">
      </el-table-column>
      <el-table-column
          prop="doctorName"
          label="医生姓名"
          width="100">
      </el-table-column>

      <el-table-column
          prop="maxAppointment"
          label="候诊剩余"
          width="100">
      </el-table-column>

      <el-table-column
          prop="maxQueue"
          label="队伍长度限制"
          width="110">
      </el-table-column>

      <el-table-column
          prop="isOpen"
          label="候诊状态"
          width="110">
        <template slot-scope="scope">
          {{statusChange(scope.row.isOpen)}}
        </template>

      </el-table-column>

      <el-table-column
          prop="createTime"
          label="创建日期"
          width="100">
        <template slot-scope="scope">
          {{timeChange(scope.row.createTime)}}
        </template>
      </el-table-column>
      <el-table-column
          label="患者队列"
          width="100">
        <el-button
            slot-scope="scope"
            @click="showMoreInfo(scope.row)">
          查看
        </el-button>
      </el-table-column>

      <el-table-column
          width="150px"
          label="操作">
        <template slot-scope="scope">
          <el-button type="text"
                     @click="editHandle(scope.row.queueId)"
          >编辑</el-button>

          <el-divider direction="vertical"></el-divider>

          <el-popconfirm title="确定要删除这条记录吗？"
                         @confirm="delHandle(scope.row.queueId)">
            <el-button type="text" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--页码-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>


    <!--其他信息弹出框-->
    <el-dialog :visible.sync="showMoreInfoDig"
               title="患者信息">

      <el-descriptions
          :column="2"
          border
          direction="vertical" v-for="item in moreInfo.patientQueue">
        <el-descriptions-item >
          <template slot="label">
            <i class="el-icon-document"></i>
            患者id
          </template>
          {{textChange(item.patientId)}}
        </el-descriptions-item>

        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-document"></i>
             患者姓名
          </template>
          {{textChange(item.realName)}}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!--编辑弹窗-->
    <el-dialog title="候诊信息"
               :visible.sync="dialogFormVisible"
               width="600px"
               @closed="resetForm('editForm')">
      <el-form :model="editForm"
               :rules="editFormRules"
               ref="editForm">
        <el-form-item label="医生id" prop="doctorId" label-width="100px">
          <el-input v-model="editForm.doctorId"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="候诊剩余" prop="maxAppointment" label-width="100px">
          <el-input v-model="editForm.maxAppointment"
                    autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="队伍长度限制" prop="maxQueue" label-width="100px">
          <el-input v-model="editForm.maxQueue"
                    autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="候诊状态" prop="isOpen" label-width="100px">
          <el-select v-model = "editForm.isOpen"
                    autocomplete="off">
            <el-option :value="true" label="开启">
            </el-option>
            <el-option :value="false" label="关闭">
            </el-option>

          </el-select>
        </el-form-item>

        <el-form-item label="患者队列" prop="patientQueue" label-width="100px">
          <el-input v-model="editForm.patientQueue"
                    autocomplete="off" placeholder="以'#' 隔开 患者id, 结尾为'#' "></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('editForm')">取 消</el-button>
        <el-button type="primary" @click.native="submitEditForm('editForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: "waitingQueueManagement",
  data(){

    let validateId = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('绑定的用户账号'));
      }
      let regex = /^\d{5,}$/;
      if(!regex.test(value)){
        callback(new Error('非合法账号格式'));
      }
      callback();
    };

    let validateQueue =(rule, value, callback)=>{
      if (value === ''){
        callback(new Error('队列不为空'));
      }
      if(value < 10 || value > 30){
        callback(new Error('队列长度区间[10,30]'));
      }
      callback();
    }

    let validateAppointment =(rule, value, callback)=>{
      if (value === ''){
        callback(new Error('队列不为空'));
      }
      if(value < 0 || value > 60){
        callback(new Error('当日出诊次数区间[0,60]'));
      }
      callback();
    }

    let validateIsOpen= (rule, value, callback)=>{
      if(value === ''){
        callback(new Error('开诊状态不为空'));
      }
      callback();
    }


    return{
      //更多消息窗
      showMoreInfoDig: false,
      //删除键
      delBtnStu: true,
      //编辑窗
      dialogFormVisible: false,

      //搜索对象
      searchForm: {
        data: '',
        method: "all-page",
        params: {
          current: this.current,
          key: '',
          id: 0,
          name: '',
          size: this.size
        }
      },
      //数据
      ListInfo: [
        {
          queueId: 0,
          doctorId: 0,
          doctorName: '',
          maxQueue: 0,
          maxAppointment: 0,
          createTime: '',
          updateItem: '',
          isOpen: false,

          patientQueue: '',
        }
      ],

      //候诊显示
      moreInfo:{ //patientId
        patientQueue: [
          {
            patientId: '',
            realName: '',
          }
        ]
      },

      patientList: [
        {
          id: 0,
          name: '',
        }
      ],

      //编辑窗口数据
      editForm: {
        queueId: 0,
        doctorId: 0,
        maxQueue: 0,
        maxAppointment: 0,
        createTime: '',
        updateItem: '',
        isOpen: false,

        patientQueue: '',
      },

      editFormRules: {
        queueId: [
          {required: true,validator: validateId , trigger: 'blur'}
        ],

        doctorId: [
          {required: true,validator: validateId , trigger: 'blur'}
        ],

        // patientQueue: [
        //   {required: true,validator: validateId, trigger: 'blur'}
        // ],
        maxQueue: [
          {required: true,validator: validateQueue, trigger: 'blur'}
        ],
        maxAppointment: [
          {required: true, validator: validateAppointment, trigger: 'blur'}
        ],
        isOpen: [
          {required: true, validator: validateIsOpen , trigger: 'blur'}
        ]

      },

      current: 1,
      total: 0,
      size: 10,

    }
  },
  created() {
    this.getListInfo();
  }
  ,methods: {
    getListInfo(){
      const self = this;
      let key = this.searchForm.params.key;
      let way = 'all-page';
      let idVal = 0;
      let nameVal = '';

      let regexName = /^[\u4E00-\u9FA5]+$/;
      let regexNum = /^\d{5,}$/;

      if(regexName.test(key)){
        way = 'name-page';
        nameVal = key.toString();
      }
      else if(regexNum.test(key)){
        way = 'id-page';
        idVal = Number(key);
      }

      let json = {
        method: way ,
        params: {
          'id': idVal,
          'name': nameVal,
          'current': self.current,
          'size': self.size
        }
      }

      self.$axios.post('api/waitingQueue/findQueueInfo',json)
          .then(res=>{
            self.ListInfo = res.data.data.data;
            self.current = res.data.data.currentPage;
            self.size = res.data.data.size;
            self.total = res.data.data.total;
          }).catch(err => {
        console.log(err)
      })

    },

    delHandle(id) {
      let ids = []
      id ? ids.push(id) : this.multipleSelection.forEach(row => {
        ids.push(row.queueId)
      })
      console.log(ids)
      let url = 'api/waitingQueue/deleteQueueInfo'

      this.$axios.post(url, {'ids': ids}).then(res => {

        this.$message({
          showClose: true,
          message: '恭喜你，操作成功',
          type: 'success',
          onClose: () => {
            this.getListInfo()
          }
        });
      })
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(rows) {
      this.multipleSelection = rows;
      this.delBtnStu = rows.length === 0
    },
    editHandle(id){
      console.log(id)
      let json = {
        'waitingQueueId': id
      }
      this.$axios.post("api/waitingQueue/selectWaitingQueueById",json).then(res => {
        this.editForm = res.data.data
        this.dialogFormVisible = true
      })

    },
    //换显示数
    handleSizeChange(val) {
      this.size = val
      this.getListInfo()
    },
    //换页
    handleCurrentChange(val) {
      this.current = val
      this.getListInfo()
    },
    //重置弹出表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.editForm = {}
      this.dialogFormVisible = false
      this.permDialogFormVisible = false
    },
    //提交编辑
    submitEditForm(formName){
      console.log(this.editForm.queueId);

      let choice = (Number(this.editForm.queueId) !== 0
          && this.editForm.queueId !== undefined
          && String(this.editForm.queueId) !== '');

      this.$refs[formName].validate((valid) => {
        console.log("edit")
        if (valid) {
          this.$axios.post('api/waitingQueue/' + ( choice
              ? "modifyQueueInfo"
              : "addQueueInfo") ,this.editForm)
              .then(res => {
                console.log(res.data)
                this.resetForm(formName)
                this.$message({
                  showClose: true,
                  message: '恭喜你，操作成功',
                  type: 'success',
                  onClose: () => {
                    this.getListInfo()
                  }
                });
              })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    showMoreInfo(val){
      const self = this;
      let queue = val.patientQueue;
      let data = {
        'patientQueue': queue};

      this.$axios.post('api/waitingQueue/getPatientQueue',data)
          .then(res => {
            self.moreInfo.patientQueue = res.data.data;
            self.showMoreInfoDig = true;

          }).catch(err => {
        console.error("[error]")
        console.log(err);
      })

    },
    timeChange(val){
      let str = val.toString();
      str = str.substring(0,19).replace('T',' ');

      return str;

    },
    textChange(val){
      if(val === null){
        return '暂无信息';
      }
      return val;
    },
    statusChange(val){
      let choice = Boolean(val);
      return choice ? '开启':'关闭'
    }

  }
}
</script>

<style scoped>
  .management{
    margin: 15px 15px;
  }
  .el-pagination{
    margin: 0 auto; text-align: center;
    /*margin-top: 22px;*/
  }
</style>